﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.U2D;
using DG.Tweening;

/// <summary>
/// 运羊毛
/// </summary>
public class TransportSheepFeather
{
    private TenPlusModuleRuntimeData runtimeData;

    private int sum;

   private GameRound gameround;

    private GameObject sceneObj;

    private GameObject config;

    private GameObject car;

    private List<GameObject> boxes = new List<GameObject>();

    private int factor1;
    private int factor2;

    private GameObject Ledi;
    private Animator lediAni;

    private float lastOperateTime;

    private GameObject sahuaObj;
    /// <summary>
    /// 加载场景
    /// </summary>
    /// <param name="r">该回合信息</param>
    /// <param name="s">算术之和</param>
    /// <param name="trd">运行时数据</param>
    public TransportSheepFeather(GameRound r, int s, TenPlusModuleRuntimeData trd)
    {
        Reset(r,s,trd);
    }

    //初始化
    public void Reset(GameRound r, int s, TenPlusModuleRuntimeData trd)
    {
        gameround = r;
        sum = s;
        runtimeData = trd;

        //1.加载场景资源
        LoadScene();

        //2.加载配置数据
        LoadConfigData();

        //3.加载车，箱子
        LoadCarAndBox();

        //4.车，箱子上面的算式赋值
        InitCarAndBox();

        //5.初始化勋章个数
        LoadHonor();

        //6.加载乐迪
        LoadLedi();

        //7.注册事件
        Register();

        //8.游戏开始
        GameStart();
    }

    #region 加载


    //加载乐迪
    void LoadLedi()
    {
        if (Ledi == null)
        {
            Ledi = new GameObject("ledi(3)");
            Resource r = ResourceManager.Instance.GetResource(TenPlusModuleAssetPath.ledi, typeof(GameObject), enResourceType.Prefab);
            GameObject lediModel = GameObject.Instantiate(r.m_content) as GameObject;
            lediModel.transform.SetParent(Ledi.transform);
            lediAni = lediModel.GetComponent<Animator>();
            Ledi.transform.position = config.transform.Find("ledi/1").position;
            Ledi.transform.localRotation = config.transform.Find("ledi/1").localRotation;
        }
    }

    void LoadHonor()
    {
        HUIEvent param = new HUIEvent();
        param.m_eventID = enUIEventID.AddPlus_Image_XunZhangAdd;
        param.m_eventParams.argInt = runtimeData.currentRoundIndex;
        HUIEventManager.Instance.DispatchUIEvent(param);
    }

    //加载场景
    void LoadScene()
    {
        Resource r;
        r = ResourceManager.Instance.GetResource(TenPlusModuleAssetPath.TransportFeatherScene, typeof(GameObject), enResourceType.ScenePrefab);
        if (sceneObj == null)
            sceneObj = GameObject.Instantiate(r.m_content) as GameObject;
        sceneObj.SetActive(true);
    }

    void LoadConfigData()
    {
        Resource r;
        r = ResourceManager.Instance.GetResource(TenPlusModuleAssetPath.TransportFeatherConfigData, typeof(GameObject), enResourceType.Prefab);
        if (config == null)
            config = GameObject.Instantiate(r.m_content) as GameObject;
        
    }

    //加载汽车和盒子
    void LoadCarAndBox()
    {
        Resource r;
        r = ResourceManager.Instance.GetResource(TenPlusModuleAssetPath.TransportFeather_Car, typeof(GameObject), enResourceType.Prefab);
        car = GameObject.Instantiate(r.m_content) as GameObject;
        car.transform.position = config.transform.Find("car/1/1").position;
        car.AddComponent<CarModule>();
        car.GetComponent<Collider>().enabled = false;

        GameObject go;
        r = ResourceManager.Instance.GetResource(TenPlusModuleAssetPath.TransportFeather_Box, typeof(GameObject), enResourceType.Prefab);
        for (int i = 0; i < 3; i++)
        {
            go = GameObject.Instantiate(r.m_content) as GameObject;
            go.transform.position = config.transform.Find("box").GetChild(i).GetChild(0).position;
            boxes.Add(go);
            go.GetComponent<Collider>().enabled = false;
        }

    }

    //初始化车和盒子上的算式
    void InitCarAndBox()
    {
        SetCarTexture();
        SetBoxTexture();
    }

    //设置卡车上的算式图片
    void SetCarTexture()
    {

        factor1 = UnityEngine.Random.Range(1, sum);
        factor2 = sum - factor1;

        GameObject f1 = car.transform.Find(string.Format("{0}", "303030301")).gameObject;
        GameObject f2 = car.transform.Find(string.Format("{0} {1}", "303030301", 1)).gameObject;

        Texture t1 = Resources.Load<Texture>(TenPlusModuleAssetPath.boxNumbers[factor1 - 1]);
        f1.GetComponent<SkinnedMeshRenderer>().material.mainTexture = t1;
        Texture t2 = Resources.Load<Texture>(TenPlusModuleAssetPath.boxNumbers[factor2 - 1]);
        f2.GetComponent<SkinnedMeshRenderer>().material.mainTexture = t2;

        
    }

    //设置箱子上的结果图片
    void SetBoxTexture()
    {
        //获得三个算式结果集
        string str = MathHelp.GetThreeNoSameNumber(1, 10, sum);//[]
        string[] list = str.Split(',');
        for (int i = 0; i < list.Length; i++)
        {
            int tmp = int.Parse(list[i]);
            boxes[i].AddComponent<BoxModule>().Init(tmp,i);
            GameObject g = boxes[i].transform.Find(string.Format("{0} {1}", "303030302", 1)).gameObject;
            Texture t = Resources.Load<Texture>(TenPlusModuleAssetPath.boxNumbers[tmp - 1]);
            g.GetComponent<MeshRenderer>().material.mainTexture = t;
        }
    }

    //注册事件
    void Register()
    {
        HUIEventManager.Instance.AddUIEventListener(enUIEventID.AddPlus_Box_Click, BoxClick);
        HUIEventManager.Instance.AddUIEventListener(enUIEventID.AddPlus_Car_Click, CarClick);
        HUIEventManager.Instance.AddUIEventListener(enUIEventID.AddPlus_RoundOver, this.RoundOver);
    }

    //移除事件
    void RemoveListener()
    {
        HUIEventManager.Instance.RemoveUIEventListener(enUIEventID.AddPlus_Box_Click, BoxClick);
        HUIEventManager.Instance.RemoveUIEventListener(enUIEventID.AddPlus_Car_Click, CarClick);
        HUIEventManager.Instance.RemoveUIEventListener(enUIEventID.AddPlus_RoundOver, this.RoundOver);
    }

    #endregion

    #region 超时处理

    /// <summary>
    /// 开启总计时器
    /// </summary>
    void StartTimer()
    {
        lastOperateTime = Time.realtimeSinceStartup;
        TimerManager.Instance.AddTimer(100, int.MaxValue, Detect);
    }

    void UpdateOperateTime(HUIEvent hUIEvent)
    {
        Updatetime();
    }

    void Updatetime()
    {
        lastOperateTime = Time.realtimeSinceStartup;
    }


    private void Detect(int timerSequence)
    {
        if (Time.realtimeSinceStartup - lastOperateTime > TenPlusModuleAssetPath.timeout)
        {
            Debug.Log("超时了.");
            lastOperateTime = Time.realtimeSinceStartup;
            //我们将羊毛放到对应的货车上吧
            AudioManager.Instance.PlaySound(TenPlusModuleAssetPath.audio_403030304);
        }
    }

    void RemoveTimer()
    {
        TimerManager.Instance.RemoveTimer(this.Detect);
    }

    #endregion

    #region 流程


    //游戏开始
    void GameStart()
    {
        //加载乐迪
        //播放音乐&乐迪开心动作
        //汽车驶入
        //箱子驶入
        //开始点击

        //限定:第一个回合有乐迪提示
        if (runtimeData.currentRoundIndex == 0)
        {
            //乐迪
            //播放音乐&乐迪动画
            //乐迪离开

            StartIndtroduce();
        }
        else
        {
            CarIn();
        }

    }

    //开场介绍 music&乐迪介绍动画
    void StartIndtroduce()
    {
        Vector3 endPos = config.transform.Find("ledi/2").position;
        Ledi.transform.DOMove(endPos, TenPlusAnimLength.lediEnterTime).SetEase(Ease.Flash).OnComplete(() =>
        {
            //播放动画
            lediAni.CrossFade(TenPlusModuleAssetPath.anim_ledi_happy, TenPlusAnimLength.animationCrossTime);
            float showtime = AddPlusController.GetAudioClipLength(TenPlusModuleAssetPath.audio_403030301);
            float anitime = AddPlusController.GetAnimationClipLength(lediAni.runtimeAnimatorController, TenPlusModuleAssetPath.anim_ledi_happy) + 0.2f;
            showtime = showtime > anitime ? showtime : anitime;
            AudioManager.Instance.PlaySound(TenPlusModuleAssetPath.audio_403030301);
            TimerManager.Instance.AddTimer(showtime, HideLedi);
        });
    }

    void HideLedi()
    {
        Vector3 endPos = config.transform.Find("ledi/1").position;
        Ledi.transform.DOMove(endPos, TenPlusAnimLength.lediExitTime).SetEase(Ease.Flash).OnComplete(() =>
        {
            CarIn();
        });

    }

    void BoxClick(HUIEvent hUIEvent)
    {
        //Debug.Log(hUIEvent.m_eventParams.argInt);
        if (hUIEvent.m_eventParams.argInt == sum)
        {
            //点击正确
            //Debug.Log("点击正确");
            //箱子自动装到汽车上&播放语音
            //汽车开走
            //[完成一轮时出现的交互:播放语音&击掌动画]    
            //学习进度+1

            //播放语音:你真棒，我们继续吧
            AudioManager.Instance.PlaySound(TenPlusModuleAssetPath.audio_403030204);
            Vector3 endPos = car.transform.Find("box").position;
            boxes[hUIEvent.m_eventParams.argInt2].GetComponent<Collider>().enabled = false;
            boxes[hUIEvent.m_eventParams.argInt2].transform.DOMove(endPos, 1.5f).SetEase(Ease.Flash).OnComplete(()=> 
            {
                DispatchXunzhangAnim();
                GameObject.DestroyImmediate(boxes[hUIEvent.m_eventParams.argInt2]);
                
            });
        }
        else
        {
            //点击错误
            //箱子抖动
            //播放语音
            AudioManager.Instance.PlaySound(TenPlusModuleAssetPath.audio_403030302);
        }
    }

    void DispatchXunzhangAnim()
    {
        //发送勋章+1的消息
        HUIEvent ev = new HUIEvent();
        ev.m_eventID = enUIEventID.AddPlus_StartMove_Xunzhang;
        ev.m_eventParams.argInt = runtimeData.currentRoundIndex + 1;
        HUIEventManager.Instance.DispatchUIEvent(ev);
    }

    void RoundOver(HUIEvent hUIEvent)
    {
        Vector3 endPos;
        for (int i = 0; i < boxes.Count; i++)
        {
            if (boxes[i] != null)
            {
                endPos = config.transform.Find("box").GetChild(i).GetChild(0).position;
                boxes[i].transform.DOMove(endPos, 1f).SetEase(Ease.Flash);
            }
        }

        endPos = config.transform.Find("car/1/3").position;
        GameObject dust = car.transform.Find("dust").gameObject;
        dust.SetActive(true);
        //Transform lunzi1 = car.transform.Find("303030301_lunzi01");
        //Transform lunzi2 = car.transform.Find("303030301_lunzi02");
        //Animator carani = car.GetComponent<Animator>();
        car.transform.DOMove(endPos, 1.5f).SetEase(Ease.InOutQuart).OnComplete(() =>
        {
            dust.SetActive(false);
            //回合结束
            AudioManager.Instance.PlaySound(TenPlusModuleAssetPath.audio_403030303);
            Debug.Log("回合结束");
            if (IsNeedClapInteractive())
            {
                //显示击掌交互
                Clap();
            }
            else
            {
                TheEnd();
            }
        });
    }

    //是否需要击掌
    void Clap()
    {
        //加载乐迪击掌模型
        //击掌特效
        //等待击掌
        Ledi.SetActive(true);
        Ledi.transform.position = config.transform.Find("ledi/2").position;
        lediAni.SetBool("enterClap", true);
        float clapAnimLength = AddPlusController.GetAnimationClipLength(lediAni.runtimeAnimatorController, TenPlusModuleAssetPath.anim_ledi_clap);
        TimerManager.Instance.AddTimer(clapAnimLength, ShowClapBowen);
    }

    void ShowClapBowen()
    {
        GameObject effect = Ledi.transform.GetChild(0).Find("Effect").gameObject;
        effect.SetActive(true);
        effect.AddComponent<AddPlusLedi>().Setup(ClapOver);
    }

    void ClapOver()
    {
        GameObject effect = Ledi.transform.GetChild(0).Find("Effect").gameObject;
        effect.SetActive(false);
        GameObject.Destroy(effect.GetComponent<AddPlusLedi>());
        lediAni.CrossFade(TenPlusModuleAssetPath.anim_ledi_clap2, TenPlusAnimLength.animationCrossTime);
        //音效 啪
        AudioManager.Instance.PlaySound(TenPlusModuleAssetPath.audio_603030501);
        //撒花特效
        FlowerShow();
    }

    void FlowerShow()
    {
        Resource r;
        r = ResourceManager.Instance.GetResource(TenPlusModuleAssetPath.sahua, typeof(GameObject), enResourceType.Prefab);
        sahuaObj = GameObject.Instantiate(r.m_content) as GameObject;
        sahuaObj.transform.position = config.transform.Find("sahua").transform.position;

        TimerManager.Instance.AddTimer(1f, TheEnd);
    }

    void TheEnd()
    {
        DoClean();
        //发送 游戏数据改变信息
        HUIEventManager.Instance.DispatchUIEvent(enUIEventID.AddPlus_GameProcedure_Change);
    }

    //是否需要击掌交互
    bool IsNeedClapInteractive()
    {
        if (runtimeData.currentRoundIndex == 3)
            return true;
        else
            return false;
    }

    void CarIn()
    {
        Animator carani = car.GetComponent<Animator>();
        Vector3 endPos = config.transform.Find("car/1/2").position;
        //汽车移动音效
        float showtime = AddPlusController.GetAudioClipLength(TenPlusModuleAssetPath.audio_603030301);
        AudioManager.Instance.PlaySound(TenPlusModuleAssetPath.audio_603030301);
        GameObject dust = car.transform.Find("dust").gameObject;
        dust.SetActive(true);
        car.transform.DOMove(endPos, showtime).SetEase(Ease.InOutQuart).OnComplete(()=> 
        {
            //汽车停止音效
            AudioManager.Instance.PlaySound(TenPlusModuleAssetPath.audio_603030302);
            //关闭轮子
            carani.CrossFade(TenPlusModuleAssetPath.car_animations[2],TenPlusAnimLength.animationCrossTime);
            //关闭灰尘
            dust.SetActive(false);
            BoxIn();
        });
    }

    void BoxIn()
    {
        Vector3 endPos;
        float time = AddPlusController.GetAudioClipLength(TenPlusModuleAssetPath.audio_603030102);
        //箱子进入音效
        AudioManager.Instance.PlaySound(TenPlusModuleAssetPath.audio_603030102);
        for (int i=0;i<boxes.Count;i++)
        {
            endPos = config.transform.Find("box").GetChild(i).GetChild(1).position;
            boxes[i].transform.DOMove(endPos, time).SetEase(Ease.Flash);
        }
        
        TimerManager.Instance.AddTimer(time, EnableCarAndBoxes);
    }

    void EnableCarAndBoxes()
    {
        //加波纹特效。点击一次就消失
        car.GetComponent<Collider>().enabled = true;
        for (int i=0;i<boxes.Count;i++)
        {
            boxes[i].GetComponent<Collider>().enabled = true;
        }
    }

    bool islock = false;
    void CarClick(HUIEvent hUIEvent)
    {
        //播放算式读音&汽车抖动
        if (islock) return;
        islock = true;
        AudioClip[] audioClips = new AudioClip[3];
        audioClips[0] = AudioManager.Instance.GetAudioClip(TenPlusModuleAssetPath.GetNumberAudioname(factor1));
        audioClips[1] = AudioManager.Instance.GetAudioClip(TenPlusModuleAssetPath.audio_403030208);
        audioClips[2] = AudioManager.Instance.GetAudioClip(TenPlusModuleAssetPath.GetNumberAudioname(factor2));
        AudioManager.Instance.PlaySound(audioClips[0]);
        TimerManager.Instance.AddTimer(audioClips[0].length, () =>
             {
                 AudioManager.Instance.PlaySound(audioClips[1]);
             });
        TimerManager.Instance.AddTimer(audioClips[0].length+audioClips[1].length, () =>
        {
            AudioManager.Instance.PlaySound(audioClips[2]);
        });
        TimerManager.Instance.AddTimer(audioClips[0].length + audioClips[1].length+audioClips[2].length, () =>
        {
            islock = false;
        });

        //AudioManager.Instance.PlaySound(audioClips);

        Animator carani = car.GetComponent<Animator>();
        carani.SetBool("click",true);
        float length = AddPlusController.GetAnimationClipLength(carani.runtimeAnimatorController, TenPlusModuleAssetPath.car_animations[3]);
        TimerManager.Instance.AddTimer(length,()=> 
        {
            carani.SetBool("click", false);
        });
        
        
    }

    #endregion

    #region 善后

    //隐藏该场景
    public void HideScene()
    {
        if (sceneObj != null) sceneObj.SetActive(false);
    }

    public void DoClean()
    {
        TimerManager.Instance.RemoveAllTimer();
        GameObject.DestroyImmediate(car);
        foreach (GameObject go in boxes)
            GameObject.DestroyImmediate(go);
        boxes.Clear();
        RemoveListener();
        GameObject.DestroyImmediate(Ledi);
        GameObject.DestroyImmediate(sahuaObj);
    }

    #endregion
}
